package com.zwy.Shopping.dao.impl;

import com.zwy.Shopping.connection.DBCon;
import com.zwy.Shopping.dao.OrderDao;
import com.zwy.Shopping.model.Order;
import com.zwy.Shopping.model.OrderItem;
import org.apache.jasper.tagplugins.jstl.core.Out;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    @Override
    public List<Order> getAllOrder() {
        //获取链接
        Connection con = DBCon.getConnection();
        if (con == null) {
            System.out.println("数据库链接失败");
            return null;
        }
        //构造执行语句
        try {
            Statement stmt = con.createStatement();
            //当表名为关键字是表名应当用``包裹
            String sql = "select * from `order`";
            ResultSet rs = stmt.executeQuery(sql);
            List<Order> orders = new ArrayList<>();
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setUser(new UserDaoImpl().getUserById(rs.getInt("user_id")));
                order.setDate(rs.getDate("date"));
                order.setTotal(rs.getBigDecimal("total"));
                order.setStatus(rs.getShort("status"));
                order.setOrderItems(new OrderItemDaoImpl().getOrderItemByOrderId(rs.getInt("id")));
                orders.add(order);
            }

            return orders;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Order> getOrderByUserId(int userId) {
        //获得链接
        Connection con = DBCon.getConnection();
        if (con == null) {
            System.out.println("数据库连接失败");
            return null;
        }
        PreparedStatement pst = null;
        try {
            pst = con.prepareStatement("select * from `order` where user_id = ?");
            pst.setInt(1, userId);
            ResultSet rs = pst.executeQuery();
            List<Order> orders = new ArrayList<>();
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setUser(new UserDaoImpl().getUserById(rs.getInt("user_id")));
                order.setDate(rs.getDate("date"));
                order.setTotal(rs.getBigDecimal("total"));
                order.setStatus(rs.getShort("status"));
                order.setOrderItems(new OrderItemDaoImpl().getOrderItemByOrderId(rs.getInt("id")));
                orders.add(order);
            }
            return orders;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
//我的思考,关于生成订单
    //1.用户可能一次购买多种商品,每一种都购买多件商品
    //2.只生成1个订单
    //3.生成多的订单明细,具体个数取决于商品的种类
    //4.所以要传入两个一维数组实参而且大小必须一致,以便一一对应,
    //5.实操

    @Override
    public int generateOrder(int userId, BigDecimal total) {
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            con = DBCon.getConnection();
            if (con == null) {
                throw new RuntimeException("数据库连接失败");
            }
            //注意一些关键字必须用``包起来
            pst = con.prepareStatement("INSERT INTO `order` (user_id, total, `date`, status) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
            pst.setInt(1, userId);
            pst.setBigDecimal(2, total);
            pst.setTimestamp(3, new Timestamp(new Date().getTime())); // 使用 Timestamp 如果需要包含时间
            pst.setInt(4, 1);

            int affectedRows = pst.executeUpdate();
            if (affectedRows > 0) {
                rs = pst.getGeneratedKeys();
                if (rs.next()) {
                    System.out.println("添加成功");
                    //注意这里不能使用列名id,因为getGeneratedKeys() 返回的 ResultSet 只包含由数据库自动生成的键的列，而这些列可能没有实际的列名
                    return rs.getInt(1); // 通常索引从1开始，表示第一列
                }
            }
            System.out.println("未生成自增ID或插入操作未成功");
            return 0;
        } catch (SQLException e) {
            e.printStackTrace(); // 或者使用日志记录器记录错误
            throw new RuntimeException("数据库操作失败: " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (pst != null) pst.close();
            } catch (SQLException e) {
                e.printStackTrace(); // 记录关闭资源时的异常（如果发生）
            }
        }
    }


    @Override
    public boolean cancelOrder(int  orderId) {
        Connection con = DBCon.getConnection();
        int cancelOrderNumber = 0;
        PreparedStatement pst = null;
        if(con == null){
            System.out.println("链接失败");
            return false;
        }
        try {
            pst = con.prepareStatement("delete  from order_item where order_id = ?");
            pst.setInt(1,orderId);
            cancelOrderNumber = pst.executeUpdate();
            System.out.println("安全删除" + cancelOrderNumber + "个订单明细");
            pst = con.prepareStatement("delete from `order` where id = ?");
            pst.setInt(1, orderId);
            cancelOrderNumber = pst.executeUpdate();
            System.out.println("安全删除" + cancelOrderNumber + "个订单");
            return true;
        } catch (SQLException e) {
            e.getMessage();
            throw new RuntimeException(e);
        }

    }

    @Override
    public Order getOrderById(int orderId) {
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement pst = null;
        con = DBCon.getConnection();
        if(con ==null){
            System.out.println("数据库连接失败");
        }
        try {
            pst = con.prepareStatement("select * from `order` where id = ?");
            pst.setInt(1,orderId);
            rs = pst.executeQuery();
            Order order = new Order();
            if(rs.next()){
                order.setId(orderId);
                order.setOrderItems(new OrderItemDaoImpl().getOrderItemByOrderId(orderId));
                return  order;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
      return null;
    }
}
